package com.leo.javase.thread.itcast;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * ThreadLocal 
 * @author Lian
 *
 */
public class ThreadLocalTest {
	private static ThreadLocal<Integer> tl = new ThreadLocal<Integer>();
	
	/**
	 * main方法
	 * @param args
	 */
	public static void main(String[] args) {
		for(int i=0; i<2; i++){
			new Thread(new Runnable() {
				@Override
				public void run() {
					int data = new Random().nextInt(10000);
					System.out.println(Thread.currentThread().getName()+" has put data:"+data);
					//tl.set(data);
					
					MyThreadScopeData.getThreadInstance().setName("name-"+data);
					MyThreadScopeData.getThreadInstance().setAge(data);
					
					new A().get();
					new B().get();
				}
			}).start();
		}
	}
	/**
	 * 模块A
	 * @author Lian
	 */
	static class A{
		public void get(){
			//int data = tl.get();
			//System.out.println("A from "+Thread.currentThread().getName()+" has get data:"+data);
			System.out.println("A from "+Thread.currentThread().getName()+MyThreadScopeData.getThreadInstance());
		}
	}
	/**
	 * 模块B
	 * @author Lian
	 */
	static class B{
		public void get(){
			//int data = tl.get();
			//System.out.println("B from "+Thread.currentThread().getName()+" has get data:"+data);
			System.out.println("B from "+Thread.currentThread().getName()+MyThreadScopeData.getThreadInstance());
		}
	}
	
}
class MyThreadScopeData{
	
	//ThreadLocal对象
	private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();
	
	//构造函数私有化
	private MyThreadScopeData(){}
	
	//静态工厂方法
	public static MyThreadScopeData getThreadInstance(){
		MyThreadScopeData instance = map.get();
		if(null == instance){
			instance = new MyThreadScopeData();
			map.set(instance);
		}
		return instance;
	}
	
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "MyThreadScopeData [name=" + name + ", age=" + age + "]";
	}
}

